﻿using Controler;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Specialized;
using System.ServiceProcess;
using System.Threading.Tasks;

namespace BingDesktop
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Session0Through.CreateProcess($"{AppDomain.CurrentDomain.BaseDirectory}Worker.exe", null);
            RunProgramRunExample().GetAwaiter().GetResult();
        }

        protected override void OnStop()
        {
            StopProgramRunExample().GetAwaiter().GetResult();
        }

        static IScheduler scheduler;
        private static async Task RunProgramRunExample()
        {
            // Grab the Scheduler instance from the Factory
            NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            scheduler = await factory.GetScheduler();

            // and start it off
            await scheduler.Start();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<BackJob>()
                .WithIdentity("job1", "group1")
                .Build();

            // Trigger the job to run now, and then repeat every 10 seconds
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .StartNow()
                .WithCronSchedule($"{new XmlHelper().Read(Setting.ServiceCron)}")
                .Build();

            // Tell quartz to schedule the job using our trigger
            await scheduler.ScheduleJob(job, trigger);
        }

        private static async Task StopProgramRunExample()
        {
            if (scheduler != null)
                await scheduler.Shutdown();
        }
    }
}
